package callback

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

private fun download(url: String, onSuccess: (String) -> Unit, onFailure: (Exception) -> Unit): Thread {
    val thread = object : Thread() {
        override fun run() {
            try {
                sleep(1000)
                onSuccess(url)
            } catch (e: Exception) {
                onFailure(e)
            }
        }
    }
    thread.start()
    return thread
}

private suspend fun callCancellable(): String {
    return suspendCancellableCoroutine {
        val thread = download(
            "",
            onSuccess = { url ->
                it.resume(url)
            },
            onFailure = { e ->
                it.resumeWithException(e)
            }
        )
        it.invokeOnCancellation {
            // TODO 异常时
            thread.interrupt()
        }
    }
}

private suspend fun call(): String {
    // 回调 转化成 挂起函数
    return suspendCoroutine {
        download(
            "",
            onSuccess = { url ->
                it.resume(url)
            },
            onFailure = { e ->
                it.resumeWithException(e)
            }
        )
    }
}

fun main(args: Array<String>) {
    runBlocking {
        call()
        callCancellable()
    }
}